#include <utility>

#include <mainwindow.h>
#include <iostream>
#include "ui_mainwindow.h"
#include <boost/interprocess/ipc/message_queue.hpp>
#include <src/common/base/slog.hpp>

MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow) {

    ui->setupUi(this);
    this->front_message_timer = new QTimer(this);
    this->back_message_timer = new QTimer(this);
    this->front_message_timer->setInterval(100);
    this->back_message_timer->setInterval(100);
    connect(this->front_message_timer, SIGNAL(timeout()), ui->CameraViewerFront, SLOT(update_image()));
    connect(this->back_message_timer, SIGNAL(timeout()), ui->CameraViewerBack, SLOT(update_image()));

}

void MainWindow::setConfig(const std::vector<camera_t>& cameras) {

    std::vector<camera_t> _cameras=cameras;
    std::vector<std::string> _msg_queue_names;
    for (const camera_t& camera : cameras) {
        _msg_queue_names.push_back(camera.message_queue);
    }
    this->taskManager = new MobileSearch::TaskManager(cameras);
    taskManager->clear_message_queue();
    taskManager->run_worker();

    ui->CameraViewerFront->set_target_msq(_msg_queue_names.front());
    ui->CameraViewerBack->set_target_msq(_msg_queue_names.back());

}

MainWindow::~MainWindow() {
    taskManager->stop_worker();
    taskManager->clear_message_queue();
    delete ui;
}

void MainWindow::on_pushButton_start_server_clicked() {
    if (ui->edit_IP->isEnabled() and ui->edit_Port->isEnabled()) {
        ui->edit_IP->setEnabled(false);
        ui->edit_Port->setEnabled(false);
        ui->pushButton_start_server->setText("断开");
    } else {
        ui->edit_IP->setEnabled(true);
        ui->edit_Port->setEnabled(true);
        ui->pushButton_start_server->setText("连接");
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event) {
    switch (event->key()) {
        default:
            break;
    }
}

void MainWindow::keyReleaseEvent(QKeyEvent *event) {
    switch (event->key()) {
        default:
            break;
    }
}


void MainWindow::on_pushButton_BackCamera_clicked() {
    if (ui->pushButton_BackCamera->text() == "打开后摄像头") {
        ui->pushButton_BackCamera->setText("关闭后摄像头");
        this->back_message_timer->start();


    } else {
        ui->pushButton_BackCamera->setText("打开后摄像头");
        this->back_message_timer->stop();

    }
}

void MainWindow::on_pushButton_FrontCamera_clicked() {
    if (ui->pushButton_FrontCamera->text() == "打开前摄像头") {
        ui->pushButton_FrontCamera->setText("关闭前摄像头");
        this->front_message_timer->start();
    } else {
        this->front_message_timer->stop();
        ui->pushButton_FrontCamera->setText("打开前摄像头");
    }
}


